<template>
	<view class="content">
		<view class="titleView">
			<text>您好,</text>
			<text>欢迎使用免烦脑</text>
		</view>
		<view class="phone" style="margin-top: 69rpx;"><text class="inputPhone" v-text="telNum"></text></view>
		<view class="phone" style="margin-top: 24rpx;">
			<input class="inputPhone" type="number" placeholder="请输入验证码" placeholder-class="phonePlaceSytle" maxlength="4" v-model="verifCode" />
			<text class="getCode" v-if="!sendMsgDisabled" @click="getloginCode()">获取验证码</text>
			<text class="getCode" v-else>{{ codeTime }}秒后重新获取</text>
		</view>
		<!-- 提示文字 -->
		<view class="hint"><text v-text="checkText"></text></view>
		<view class="loginBtn flex-c" :class="{ shaking: toShake }" @click="login()"><text>登录</text></view>
		<view class="tipView">
			<text class="Tips1">登录注册即表示您已阅读并同意易爱</text>
			<view class="">
				<text class="Tips2" @click="toUserProtocol()">《用户协议》</text>
				<text class="Tips1">及</text>
				<text class="Tips2" @click="toPrivacyPolicy()">《隐私政策》</text>
			</view>
		</view>
	</view>
</template>

<script>
const app = getApp();
import * as api from '@/api/login';
import { isNull } from '@/utils/utils.js';
export default {
	data() {
		return {
			phone: '',
			telNum: '',
			checkText: '', //提示性文字
			verifCode: '', //验证码
			getCodeText: '获取验证码',
			phoneReg: new RegExp(/^1[3-9]\d{9}$/), //手机号正则验证
			sendMsgDisabled: false,
			codeTime: 59,
			UUID: '', //本机的UUID
			toShake: false
		};
	},
	onLoad(option) {
		console.log('onload', option);
		if (option) {
			this.telNum = option.phone;
		}
	},
	methods: {
		// 获取验证码
		getloginCode() {
			let that = this;
			//做非空判断
			let phoneNum = that.telNum;
			if (phoneNum.trim().length <= 0) {
				that.checkText = '请输入手机号';
				return;
			} else if (!that.phoneReg.test(phoneNum)) {
				that.checkText = '手机号格式错误';
				return;
			} else {
				that.checkText = '';
			}
			that.sendMsgDisabled = true;
			// 开始切换文字倒计时
			let codeInterval = setInterval(() => {
				if (that.codeTime-- <= 1) {
					that.codeTime = 59;
					that.sendMsgDisabled = false;
					clearInterval(codeInterval);
				}
			}, 1000);
			//调用接口请求验证码
			api.requestVerify(phoneNum)
				.then(function(res) {
					console.log(res);
					if (res.data.code == 2000) {
						uni.showToast({
							title: '验证码已发送，请查收!',
							icon: 'none'
						});
					} else {
						uni.showToast({
							title: '验证码错误，请重试!',
							icon: 'none'
						});
					}
				})
				.catch(function(error) {
					console.log('get verification fail', error);
				});
		},
		// 开始登录
		login() {
			let that = this;
			let phoneNum = that.telNum;
			this.checkText = '';
			if (that.verifCode.trim().length <= 0) {
				this.checkText = '请输入验证码';
				this.errorAnimation();
				return;
			} else {
				console.log('login' + that.telNum + '::' + that.verifCode);
				let obj = new Object();
				obj = {
					action: 'login',
					params: {
						role: 'EiUser',
						verification: {
							mobile: that.telNum,
							verificationCode: that.verifCode
						},
						uuid: that.$store.state.deviceUUID
					}
				};
				api.login(obj)
					.then(function(res) {
						console.log(res);
						if (res.data.code == 2000) {
							let appId = res.data.data.appIdInfo.appId;
							let appSecret = res.data.data.appIdInfo.appSecret;
							let userId = res.data.data.appIdInfo.userId;
							let userInfo = uni.getStorageSync('userInfo');
							// add new User
							userInfo.currentUser = {
								userId: userId,
								appId: appId,
								appSecret: appSecret,
								phone: that.telNum
							};
							let isNewUser = true;
							userInfo.loginUserList.forEach(item => {
								if (item.userId == userId) {
									item.appId = appId;
									item.appSecret = appSecret;
									item.phone = that.telNum;
									isNewUser = false;
								}
							});
							if (isNewUser) {
								userInfo.loginUserList.push(userInfo.currentUser);
							}
							try {
								uni.setStorageSync('userInfo', userInfo);
								that.$store.commit('userInfo', userInfo);
								that.getUserInfo();
							} catch (e) {
								//TODO handle the exception
								console.log('缓存失败', e);
							}
						} else {
							that.checkText = res.data.message;
							that.errorAnimation();
						}
					})
					.catch(function(error) {
						console.log('login fail', error);
						that.checkText = '请求出错';
					});
			}
		},
		// 错误按钮动画
		errorAnimation() {
			this.toShake = true;
			setTimeout(() => {
				this.toShake = false;
			}, 2000);
		},
		getUserInfo() {
			let that = this;
			let userId = this.$store.state.userInfo.currentUser.userId;
			let tokenId = uni.getStorageSync('tokenId');
			let data = {
				userId: userId,
				token: tokenId,
				action: 'getUserInfo'
			};
			//调用接口请求个人信息
			api.getUserInfo(data)
				.then(function(res) {
					console.log('getUserInfo::', res);
					if (res.data.message == 'userInfo is null') {
						//用户未填写个人信息  跳
						uni.redirectTo({
							url: '../../../login/fillHealhyRecords/fillHealhyRecords'
						});
					} else if (res.data.code == 2000) {
						that.$store.commit('userBaseInfo',res.data.data)
						// 关闭蓝牙
						if (that.$store.state.isConnected) app.closeBLEConnection();
						//刷新程序
						uni.reLaunch({
							url: '../../../index/index',
							success() {
								console.log('relaunch success');
							}
						});
					}
				})
				.catch(function(error) {
					console.log('get userInfo fail', error);
				});
		},
		// 用户协议
		toUserProtocol() {
			console.log('用户协议');
		},
		// 隐私政策
		toPrivacyPolicy() {}
	}
};
</script>

<style>
page {
	background-color: #f5f5f5;
}

.content {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
}
.flex-c {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
}
.titleView {
	margin-top: 22rpx;
	width: 700rpx;
	display: flex;
	flex-direction: column;
}

.titleView text {
	font-size: 56rpx;
	font-family: Source Han Sans CN;
	font-weight: bold;
	color: #333333;
	margin-left: 15rpx;
}

.phone {
	width: 700rpx;
	height: 122rpx;
	background-color: #ffffff;
	border-radius: 15px;
	display: flex;
	align-items: center;
	position: relative;
}

.inputPhone {
	margin-left: 45rpx;
	font-size: 32rpx;
	font-family: Source Han Sans CN;
	font-weight: normal;
	color: #666666;
}

.phonePlaceSytle {
	font-size: 32rpx;
	font-family: Source Han Sans CN;
	font-weight: normal;
	color: #666666;
}

.getCode {
	font-size: 32rpx;
	font-family: Source Han Sans CN;
	font-weight: normal;
	color: #0659c7;
	position: absolute;
	right: 18px;
}
.hint {
	font-size: 28rpx;
	color: #f6464e;
	height: 20px;
	width: 80%;
	margin-top: 20rpx;
}
.loginBtn {
	width: 700rpx;
	height: 100rpx;
	border-radius: 50px;
	background-color: #0659c7;
	margin-top: 80rpx;
}
.loginBtn:active {
	background-color: #007aff;
}
.loginBtn text {
	font-size: 44rpx;
	font-family: Source Han Sans CN;
	font-weight: normal;
	color: #ffffff;
}
.icon_wechat {
	width: 107rpx;
	height: 107rpx;
	margin-top: 245rpx;
}
.tipView {
	position: absolute;
	bottom: 43rpx;
	display: flex;
	flex-direction: column;
	align-items: center;
}
.Tips1 {
	font-size: 18rpx;
	font-family: Source Han Sans CN;
	font-weight: normal;
	color: #666666;
}
.Tips2 {
	font-size: 18rpx;
	font-family: Source Han Sans CN;
	font-weight: normal;
	color: #0659c7;
}
</style>
